<script setup lang="ts">
import { ref, Ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getSendMsgCode, getCheckCode } from '../../api/user'
import { showToast } from 'vant'

const router = useRouter()

// 记录倒计时时间
const time: Ref<number> = ref(10)
// 标记按钮上的内容
const text: Ref<string> = ref('发送验证码')
// 记录定时器的变量
const timer: any = ref(null)

// 点击发送验证码的事件
function sendCodeFn() {

  getSendMsgCode({ tel: localStorage.getItem('tel') || '' }).then(res => {
    console.log(res);

    timer.value = setInterval(() => {
      time.value--
      text.value = time.value + 's 后获取'
      if (time.value < 1) {
        // 关闭定时器
        clearInterval(timer.value)
        // 将时间改为默认时间
        time.value = 10
        // 将按钮文字改为 发送验证码
        text.value = '发送验证码'
      }
    }, 1000)
  })



}

// 验证码
let telcode: Ref<string> = ref('')
const flag = computed(() => {
  return telcode.value.length == 5
})

// 下一步的点击事件
function onSubmit() {
  // this.$router.push()
  // router.push('/register/step3')
  // 1. 发送数据请求判断验证码是否正确
  // 2. 验证码正确后就进入设置密码页面
  // 3. 验证码错误给出提示重新输入
  getCheckCode({
    tel: localStorage.getItem('tel') || '',
    telcode: telcode.value
  }).then(res => {
    console.log(res);
    if (res.data.code == '200') {
      // 可以下一步
      showToast({ message: '验证码验证成功' })
      router.push('/register/step3')
    } else {
      // 验证码有误
      showToast({ message: res.data.message })
    }

  })
}


</script>
<template>
  <div class="box">
    <van-nav-bar class="header" title="验证码" left-text="返回" left-arrow @click-left="$router.back()" />
    <div class="content">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field v-model="telcode" label="验证码" placeholder="请输入验证码">
            <template #button>
              <van-button :disabled="time < 10" size="mini" @click="sendCodeFn">
                {{ text }}
              </van-button>
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button :disabled="!flag" round block type="danger" native-type="submit">
            下一步
          </van-button>
        </div>

      </van-form>
    </div>
  </div>
</template>
<style scoped lang="scss">
.header {
  margin-bottom: 30px;
  background-color: #f1f8e9;

}
</style>
